﻿using iTextSharp.text;
using SqlSugar;
using SqlSugar.SplitTableExtensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WaterCloud.Code;
using WaterCloud.DataBase;
using WaterCloud.Domain;
using WaterCloud.Domain.Entity.STZBManage;
using WaterCloud.Domain.Entity.STZBManage.Request;
using static iTextSharp.text.pdf.AcroFields;

namespace WaterCloud.Service.STZBManage
{
    /// <summary>
    /// 率土之滨账号服务类
    /// </summary>
    public class STZB_AccountService : BaseService<Account>, IDenpendency
    {
        public STZB_AccountService(ISqlSugarClient context) : base(context)
        {
        }

        public SsqhService _ssqhService { get; set; }

        public WeaponsInfo_Service weaponsInfo_ { get; set; }

        /// <summary>
        /// 添加账号
        /// </summary>
        /// <param name="account">账号信息</param>
        /// <returns></returns>
        public async Task Add_Account(List<Account_Request> accountList)
        {
            //批量处理数据
            foreach (var account in accountList)
            {
                account.F_Id = Guid.NewGuid().ToString("N");
                if (string.IsNullOrEmpty(account.Code) || account.Code.Equals("备战区"))
                {
                    account.State = 3;//备战区
                }
                else
                {
                    //根据区号查询试师区号是否存在值
                    int total = await _ssqhService.Code_CX(account.Code);
                    if (total > 0)
                    {
                        account.State = 1; //试师
                    }
                    else
                    {
                        account.State = 2; //征服
                    }
                }
                //根据公告时间来决定状态
                if (account.Gg_EndTime == null || account.Gg_EndTime <= DateTime.Now) account.Sell_state = 2;
                await repository.InsertSplit(account);//添加账号信息
                account.Weapons.ForEach(x => { x.F_Id = account.F_Id; }); //设置账号id
                await weaponsInfo_.AddList_WeaponsInfo(account.Weapons); //批量添加武器信息
            }
        }


        /// <summary>
        /// 修改查看状态
        /// </summary>
        /// <param name="id">数据id</param>
        /// <returns></returns>
        public async Task Update_ReadState(string id, string userid)
        {
            var account = await repository.IQueryableSplit().Where(x => x.F_Id == id).FirstAsync();
            if (account != null)
            {
                account.Read_Id += string.IsNullOrEmpty(account.Read_Id) ? (userid + ",") : account.Read_Id.Contains(userid) ? "" : (userid + ","); //已读
                await repository.UpdateSplit(account);
            }
        }

        /// <summary>
        /// 获取账号列表  
        /// </summary>
        /// <param name="state">账号状态 1:试师、2:征服</param>
        /// <param name="sell_state">出售状态 1:公示期、2:可购买</param>
        /// <param name="page">页数</param>
        /// <param name="limit">每页显示条数 默认10条</param>
        /// <returns></returns>
        public async Task<SqlSugarDataResult<Account>> GetTable(int state, int sell_state, string orderColume = "CreateTime", string order = "Desc", int page = 1, int limit = 10)
        {
            RefAsync<int> total = 0;
            var data = await repository.IQueryableSplit_Take(1) //获取第一张表
                .WhereIF(state != 0, x => x.State == state)  //账号状态 1:试师、2:征服
                .WhereIF(sell_state != 0, x => x.Sell_state == sell_state)  //出售状态 1:公示期、2:可购买
                .OrderBy(string.Format("{0} {1}", orderColume, order)) //排序方式
                .ToPageListAsync(page, limit, total);
            return new SqlSugarDataResult<Account> { List = data, Total = total };
        }

        /// <summary>
        /// 获取账号列表
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="keyword">关键词</param>
        /// <param name="sell_state">出售状态 1:公示期、2:可购买</param>
        /// <param name="read_State">读取状态</param>
        /// <param name="state">账号状态</param>
        /// <param name="monthNum">月数 默认最近一个月</param>
        /// <returns></returns>
        public async Task<List<Account>> Get_Account_GridJson(SoulPage<Account> pagination, string keyword, int sell_state, string read_State, int state_val, string timeStr, string createTime, int monthNum, string userid)
        {
            DateTime stime = DateTime.Today;
            DateTime etime = stime.AddDays(1).AddHours(23).AddMinutes(59).AddSeconds(59);
            if (!string.IsNullOrEmpty(timeStr))
            {
                string[] times = timeStr.Split('-');
                stime = DateTime.Parse(times[0]);
                etime = DateTime.Parse(times[1]);
            }
            DateTime stime2 = DateTime.Today;
            DateTime etime2 = stime.AddDays(1).AddHours(23).AddMinutes(59).AddSeconds(59);
            if (!string.IsNullOrEmpty(createTime))
            {
                string[] times = createTime.Split('-');
                stime2 = DateTime.Parse(times[0]);
                etime2 = DateTime.Parse(times[1]);
            }
            var data = repository.IQueryable()
                .WhereIF(!string.IsNullOrEmpty(keyword), x => x.Cbg_Url.Contains(keyword))
                .WhereIF(read_State == "1", x => x.Read_Id.Contains(userid)) //已读状态
                .WhereIF(read_State == "0", x => !x.Read_Id.Contains(userid)) //未读状态
                .WhereIF(state_val > 0, x => x.State == state_val)
                .WhereIF(!string.IsNullOrEmpty(timeStr), x => x.Gg_EndTime >= stime && x.Gg_EndTime <= etime)
                .WhereIF(!string.IsNullOrEmpty(createTime), x => x.CreateTime >= stime2 && x.CreateTime <= etime2)
                .WhereIF(sell_state > 0, x => x.Sell_state == sell_state)
                .SplitTable(t => t.Take(monthNum));
            //权限过滤（保证分页参数存在）
            data = GetDataPrivilege("x", "", data);
            var list = await data.ToPageListAsync(pagination);
            list.ForEach(x =>
            {
                x.Read_State = (string.IsNullOrEmpty(x.Read_Id) ? 0 : x.Read_Id.Contains(userid) ? 1 : 0);//处理读取状态
                x.Sc_State = (string.IsNullOrEmpty(x.Sc_Id) ? 0 : x.Sc_Id.Contains(userid) ? 1 : 0);//处理收藏状态
            });
            return list;
        }


        /// <summary>
        /// 删除账号数据
        /// </summary>
        /// <param name="ids">数据id，多个值使用逗号隔开</param>
        /// <returns></returns>
        public async Task Delete_Account(string ids)
        {
            var idArr = ids.Split(','); //分组
            //获取数据集合
            var dataList = await repository.IQueryable().Where(x => idArr.Contains(x.F_Id)).SplitTable().ToListAsync();
            await repository.Delete_Split(dataList);
        }

        /// <summary>
        /// 更新公示状态
        /// </summary>
        /// <returns></returns>

        public async Task UpdateGgState()
        {
            try
            {
                //获取当前系统时间 这里添加8个小时差因为发布到Liunx系统时间会有差异
                DateTime currentTime = DateTime.Now.AddHours(8);
                //获取账号已过公示期的数据
                var list = await repository.Db_Context().Queryable<Account>()
                    .Where(x => x.Sell_state == 1 && x.Gg_EndTime <= currentTime)
                    .SplitTable(t => t.Take(2)) //获取前两个月的表数据
                    .ToListAsync();
                //获取账号收藏表已过公示期的数据
                var scList = await repository.Db_Context().Queryable<Account_SC>()
                    .Where(x => x.Sell_state == 1 && x.Gg_EndTime <= currentTime)
                    .SplitTable(t => t.Take(2))//获取前两个月的表数据
                    .ToListAsync();
                if (list.Count > 0 || scList.Count > 0)
                {
                    //修改账号数据
                    list.ForEach(x => x.Sell_state = 2);
                    await repository.Db_Context().Updateable<Account>(list)
                        .SplitTable()
                        .ExecuteCommandAsync();
                    //修改收藏账号数据
                    scList.ForEach(x => x.Sell_state = 2);
                    await repository.Db_Context().Updateable<Account_SC>(scList)
                        .SplitTable()
                        .ExecuteCommandAsync();
                }
                LogHelper.WriteWithTime($"当前时间：{currentTime}、账号表共：{list.Count}条数据、账号收藏表共：{scList.Count}条数据");
            }
            catch
            {
                throw;
            }
        }


        /// <summary>
        /// 添加或取消收藏账号
        /// </summary>
        /// <param name="ids">账号id</param>
        /// <param name="type">1:收藏、2:取消收藏</param>
        /// <param name="userid">用户id</param>
        /// <returns></returns>
        public async Task AddOrEdit_Collection(string[] ids, int type, string userid)
        {
            //获取当前账号id数据
            var data = await repository.Db_Context().Queryable<Account>()
                .Where(x => ids.Contains(x.F_Id))
                .SplitTable()
                .ToListAsync();
            if (type == 1) //收藏
            {
                List<Account_SC> scList = data.Select(x => new Account_SC
                {
                    Id = Guid.NewGuid().ToString("N"),
                    F_Id = x.F_Id,
                    State = x.State,
                    Code = x.Code,
                    Sell_state = x.Sell_state,
                    Price = x.Price,
                    Tgc_Num = x.Tgc_Num,
                    Ryds_Num = x.Ryds_Num,
                    Sty_Num = x.Sty_Num,
                    Wqst_Num = x.Wqst_Num,
                    Cbwq_Num = x.Cbwq_Num,
                    Pty_Num = x.Pty_Num,
                    WeaponsNumber = x.WeaponsNumber,
                    PowderNumber = x.PowderNumber,
                    Cbg_Url = x.Cbg_Url,
                    Gg_EndTime = x.Gg_EndTime,
                    Wdzwq_Num = x.Wdzwq_Num,
                    UserId = userid,
                    CreateTime = DateTime.Now
                }).ToList();
                //开启事务
                await repository.Db_Context().Ado.BeginTranAsync();
                //批量添加收藏数据
                await repository.Db_Context().Insertable<Account_SC>(scList).SplitTable().ExecuteCommandAsync();
                data.ForEach(x => x.Sc_Id = x.Sc_Id + userid + ","); //添加用户id到收藏标识
                //将对应账号数据添加收藏标识用户id
                await repository.Db_Context().Updateable<Account>(data)
                    .SplitTable()
                    .ExecuteCommandAsync();
                //提交事务
                await repository.Db_Context().Ado.CommitTranAsync();

            }
            else if (type == 2) //取消收藏
            {
                //开启事务
                await repository.Db_Context().Ado.BeginTranAsync();
                //获取收藏数据并删除
                var list = await repository.Db_Context().Queryable<Account_SC>()
                    .Where(x => ids.Contains(x.F_Id) && x.UserId == userid)
                    .SplitTable()
                    .ToListAsync();
                //删除收藏账号数据
                await repository.Db_Context().Deleteable<Account_SC>(list)
                    .SplitTable()
                    .ExecuteCommandAsync();
                //更新账号收藏标识
                data.ForEach(x => x.Sc_Id = x.Sc_Id.Replace(userid + ",", ""));
                await repository.Db_Context().Updateable<Account>(data)
                    .SplitTable()
                    .ExecuteCommandAsync();
                //提交事务
                await repository.Db_Context().Ado.CommitTranAsync();
            }
        }

        /// <summary>
        /// 更新账号状态
        /// </summary>
        /// <returns></returns>
        public async Task UpdateState()
        {
            //获取试师区号列表
            var ssqhList = await repository.Db_Context().Queryable<Ssqh>().Select(x => x.Code).ToArrayAsync();
            var dayTime = DateTime.Today;
            //获取公示期大于等于今天的数据
            var list = await repository.Db_Context().Queryable<Account>()
                .Where(x => ssqhList.Contains(x.Code) && x.Gg_EndTime >= dayTime && x.State != 1)
                .SplitTable(t => t.Take(2)) //获取前两个月的表数据
                .ToListAsync();
            //修改账号状态为试师
            list.ForEach(x => x.State = 1);
            await repository.Db_Context().Updateable<Account>(list)
                .SplitTable()
                .ExecuteCommandAsync();
            LogHelper.WriteWithTime($"处理账号试师状态任务已触发，当前时间：{dayTime}、处理总条数：{list.Count}");
        }
    }
}
